import {defHttp} from '/@/utils/http/axios';
import { useMessage } from "/@/hooks/web/useMessage";

const { createConfirm } = useMessage();

enum Api {
  list = '/health_disease/healthDisease/list',
  save='/health_disease/healthDisease/add',
  edit='/health_disease/healthDisease/edit',
  deleteOne = '/health_disease/healthDisease/delete',
  deleteBatch = '/health_disease/healthDisease/deleteBatch',
  importExcel = '/health_disease/healthDisease/importExcel',
  exportXls = '/health_disease/healthDisease/exportXls',
}
/**
 * 导出api
 * @param params
 */
export const getExportUrl = Api.exportXls;
/**
 * 导入api
 */
export const getImportUrl = Api.importExcel;
/**
 * 列表接口
 * @param params
 */
export const list = (params) =>
  defHttp.get({url: Api.list, params});

/**
 * 删除单个
 */
export const deleteOne = (params,handleSuccess) => {
  return defHttp.delete({url: Api.deleteOne, params}, {joinParamsToUrl: true}).then(() => {
    handleSuccess();
  });
}
/**
 * 批量删除
 * @param params
 */
export const batchDelete = (params, handleSuccess) => {
  createConfirm({
    iconType: 'warning',
    title: '确认删除',
    content: '是否删除选中数据',
    okText: '确认',
    cancelText: '取消',
    onOk: () => {
      return defHttp.delete({url: Api.deleteBatch, data: params}, {joinParamsToUrl: true}).then(() => {
        handleSuccess();
      });
    }
  });
}
/**
 * 保存或者更新
 * @param params
 */
export const saveOrUpdate = (params, isUpdate) => {
  let url = isUpdate ? Api.edit : Api.save;
  return defHttp.post({url: url, params});
}

/**
 * 将扁平数据转换为树形结构
 * @param data 扁平数据数组
 * @param parentId 父级ID
 */
function buildTree(data, parentId = '0') {
  const result = [];
  for (const item of data) {
    if (item.parentId === parentId) {
      const children = buildTree(data, item.key);
      const node = {
        ...item,
        children: children.length > 0 ? children : (item.leaf ? null : [])
      };
      result.push(node);
    }
  }
  return result;
}

/**
 * 根据机构编码获取部门信息
 * @param params
 */
export const getDepartName = (params) => {
  return defHttp.get({ url: '/sys/sysDepart/getDepartName', params });
};

/**
 * 查询部门树形结构
 * @param params
 */
export const queryAllTreeListByPid = (params) => {
  return defHttp.get({ url: '/sys/sysDepart/queryAllTreeListByPid', params });
};

/**
 * 根据医院ID查询部门树形数据（新方法）
 * @param params
 */
export const queryDeptTreeByHospitalId = async (params) => {
  const response = await defHttp.get({
    url: '/nurse_dept/nurseDept/loadTreeChildrenByHisid',
    params: {
      pid: '0',  // 父级ID，0表示查询根节点
      ...params
    }
  });
  
  // 如果返回的是扁平数据，转换为树形结构
  if (response && Array.isArray(response)) {
    return buildTree(response);
  }
  
  return response;
};